<template>
  <view class="media-preview" v-if="visible">
    <!-- 顶部导航栏 -->
    <view class="preview-header">
      <view class="back-btn" @click="closePreview">
        <u-icon name="arrow-left" color="#fff" size="20"></u-icon>
      </view>
      <view class="header-title">{{ currentDisplayIndex }} / {{ props.momentList.length }}</view>
      <view class="empty"></view>
    </view>

    <!-- 媒体内容区域 -->
<swiper 
  class="media-swiper" 
  :current="currentIndex" 
  @change="onSwiperChange"
  circular
  :indicator-dots="false"
  :autoplay="false"
  vertical
>
      <swiper-item v-for="(item, index) in mediaList" :key="index">
        <view class="media-item">
          <!-- 图片 -->
          <image 
            v-if="item.type === 'image'" 
            class="media-content" 
            :src="item.url" 
            mode="aspectFit"
            @click="toggleControls"
            show-menu-by-longpress
          />
          
          <!-- 视频 -->
          <view v-else-if="item.type === 'video'" class="video-wrapper">
            <video 
              class="media-content" 
              :src="item.url" 
              :poster="item.poster"
              controls
              @click="toggleControls"
              :id="'preview-video-' + index"
            ></video>
          </view>
        </view>
      </swiper-item>
    </swiper>

    <!-- 底部信息栏 -->
    <view class="preview-footer" v-show="showControls">
      <view class="moment-info">
        <view class="user-info" v-if="currentMedia.moment">
          <u-avatar :src="currentMedia.moment.avatar" size="mini"></u-avatar>
          <text class="username">{{ currentMedia.moment.userName }}</text>
        </view>
        <view class="moment-content" v-if="currentMedia.moment">
          <text class="content-text">{{ currentMedia.moment.content }}</text>
        </view>
      </view>
    </view>
	
	<!-- 加载更多提示 -->
	<view class="loading-more" v-if="showLoading">
	  <u-loading mode="circle" color="#fff"></u-loading>
	  <text class="loading-text">正在加载更多内容...</text>
	</view>
  </view>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  momentList: {
    type: Array,
    default: () => []
  },
  startIndex: {
    type: Number,
    default: 0
  },
  startMediaIndex: {
    type: Number,
    default: 0
  },
  hasMore: {
    type: Boolean,
    default: true
  },
  onLoadMore: {
    type: Function,
    default: () => {}
  }
});

const emit = defineEmits(['close', 'change']);

// 数据响应式
const currentIndex = ref(0);
const showControls = ref(true);
const showLoading = ref(false);

// 计算属性
const currentMedia = computed(() => {
  if (mediaList.value.length > 0 && currentIndex.value < mediaList.value.length) {
    return mediaList.value[currentIndex.value];
  }
  return {};
});

const currentDisplayIndex = computed(() => {
  if (mediaList.value.length > 0 && currentIndex.value < mediaList.value.length) {
    // 找到当前媒体属于第几个动态
    const currentMomentIndex = mediaList.value[currentIndex.value].momentIndex;
    return currentMomentIndex + 1;
  }
  return 1;
});

const mediaList = computed(() => {
  const list = [];
  props.momentList.forEach((moment, momentIndex) => {
    if (moment.mediaList && moment.mediaList.length > 0) {
      moment.mediaList.forEach((media, mediaIndex) => {
        if (moment.mediaType === 1) {
          // 图片
          list.push({
            type: 'image',
            url: media.url,
            moment: moment,
            momentIndex: momentIndex,
            mediaIndex: mediaIndex
          });
        } else if (moment.mediaType === 2) {
          // 视频
          const urls = media.url.split(',');
          list.push({
            type: 'video',
            url: urls[0],
            poster: urls[1] || moment.avatar,
            moment: moment,
            momentIndex: momentIndex,
            mediaIndex: mediaIndex
          });
        }
      });
    }
  });
  return list;
});

// 方法
const closePreview = () => {
  // 关闭时暂停所有视频
  pauseAllVideos();
  emit('close');
};

// 暂停所有视频
const pauseAllVideos = () => {
  // 使用 uni.createVideoContext 来控制视频
  nextTick(() => {
    for (let i = 0; i < mediaList.value.length; i++) {
      if (mediaList.value[i].type === 'video') {
        try {
          const videoContext = uni.createVideoContext('preview-video-' + i);
          if (videoContext) {
            videoContext.pause();
          }
        } catch (e) {
          console.log('暂停视频失败:', e);
        }
      }
    }
  });
};

const playCurrentVideo = () => {
  nextTick(() => {
    if (mediaList.value[currentIndex.value] && mediaList.value[currentIndex.value].type === 'video') {
      try {
        const videoContext = uni.createVideoContext('preview-video-' + currentIndex.value);
        if (videoContext) {
          // 先暂停所有视频再播放当前视频
          pauseAllVideos();
          setTimeout(() => {
            videoContext.play();
          }, 100);
        }
      } catch (e) {
        console.log('播放视频失败:', e);
      }
    }
  });
};

const onSwiperChange = (e) => {
  currentIndex.value = e.detail.current;
  emit('change', currentIndex.value);
  
  // 播放当前视频（如果是视频的话）
  playCurrentVideo();
  
  // 检查是否需要加载更多
  if (mediaList.value.length > 0 && currentIndex.value >= mediaList.value.length - 3 && props.hasMore && !showLoading.value) {
    // 当接近最后一个时，且还有更多数据可以加载
    loadMore();
  }
};

const loadMore = () => {
  if (typeof props.onLoadMore === 'function' && props.hasMore) {
    showLoading.value = true;
    // 调用父组件的加载更多方法
    const result = props.onLoadMore();
    // 如果onLoadMore返回的是Promise，我们可以监听其完成
    if (result && typeof result.then === 'function') {
      result.finally(() => {
        showLoading.value = false;
      });
    } else {
      // 简单延迟隐藏loading状态
      setTimeout(() => {
        showLoading.value = false;
      }, 1000);
    }
  }
};

const toggleControls = () => {
  showControls.value = !showControls.value;
};

// 监听器
watch([() => props.startIndex, () => props.startMediaIndex], ([newMomentIndex, newMediaIndex]) => {
  // 根据起始的动态索引和媒体索引计算当前应该显示的媒体项
  let targetIndex = 0;
  for (let i = 0; i < mediaList.value.length; i++) {
    const media = mediaList.value[i];
    if (media.momentIndex === newMomentIndex && media.mediaIndex === newMediaIndex) {
      targetIndex = i;
      break;
    }
  }
  // 确保索引有效
  if (targetIndex >= 0 && targetIndex < mediaList.value.length) {
    currentIndex.value = targetIndex;
  }
});

watch(() => props.visible, (newVal) => {
  if (newVal) {
    showControls.value = true;
    showLoading.value = false;
    
    // 延迟播放当前视频
    setTimeout(() => {
      playCurrentVideo();
    }, 100);
  } else {
    // 当预览关闭时暂停所有视频
    pauseAllVideos();
  }
});

// 组件卸载时暂停所有视频
onUnmounted(() => {
  pauseAllVideos();
});
</script>

<style lang="scss" scoped>
.media-preview {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  z-index: 9999;
}

.preview-header {
  position: absolute;
  top: 40rpx; /* Moved down 40rpx */
  left: 0;
  width: 100%;
  height: 80rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx;
  z-index: 10000;
  background: linear-gradient(to bottom, rgba(0,0,0,0.7), transparent);

  .back-btn {
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
    background-color: rgba(0,0,0,0.3);
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .header-title {
    color: #fff;
    font-size: 28rpx;
  }

  .empty {
    width: 60rpx;
  }
}

.media-swiper {
  width: 100%;
  height: 100%;
  flex-direction: column;
}

.media-item {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.media-content {
  width: 100%;
  height: 100%;
}

.video-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.preview-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 30rpx;
  background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
  z-index: 10000;

  .moment-info {
    .user-info {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      .username {
        color: #fff;
        margin-left: 15rpx;
        font-size: 28rpx;
      }
    }

    .moment-content {
      .content-text {
        color: #fff;
        font-size: 26rpx;
        line-height: 1.5;
      }
    }
  }
}

.loading-more {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 10001;
  
  .loading-text {
    color: #fff;
    margin-top: 20rpx;
    font-size: 28rpx;
  }
}
</style>
